<?php

require_once("config/config.php");

session_start();

if(isset( $_SESSION['USER_ID'] ))
{
    $message = 'Users is already logged in';
}

$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$password = filter_var($_POST['password'], FILTER_SANITIZE_STRING);

$password = md5( $password );

try
{
    

    
    $dbh = new PDO("mysql:host=" . $server['hostname'] . ";dbname=" . $server['dbname'], $server['username'], $server['password']);
    /*** $message = a message saying we have connected ***/

    /*** set the error mode to excptions ***/
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    /*** prepare the select statement ***/
    $stmt = $dbh->prepare("select user_id, 
                                  full_name
                             from pa_users 
                            where ucase(user_name) = ucase(:username) 
                              and ucase(password)  = ucase(:password)");

    /*** bind the parameters ***/
    $stmt->bindParam(':username', $username, PDO::PARAM_STR);
    $stmt->bindParam(':password', $password, PDO::PARAM_STR, 40);

    /*** execute the prepared statement ***/
    $stmt->execute();

    /*** check for a result ***/
    //$user_id        = $stmt->fetchColumn(0);
    //$user_full_name = $stmt->fetchColumn(1);
    $row = $stmt->fetchAll();
    //print_r($row);
    $user_id = $row[0][0];
    $user_full_name = $row[0][1];       

    /*** if we have no result then fail boat ***/
    if($user_id == false)
    {
            //$message = 'Login Failed';
            $_SESSION['LOGIN_ERROR'] = "ERROR";
            header("Location: index.php");
    }
    /*** if we do have a result, all is well ***/
    else
    {
            /*** set the session user_id variable ***/
            unset($_SESSION['LOGIN_ERROR']);
            $_SESSION['USER_ID']        = $user_id;
            $_SESSION['USER_FULL_NAME'] = $user_full_name;

            /*** tell the user we are logged in ***/
            $message = 'You are now logged in';
            
            header("Location: home.php");
    }
    
}
catch(Exception $e)
{
    /*** if we are here, something has gone wrong with the database ***/
    //$message = 'We are unable to process your request. Please try again later"';
	echo "Error " . $e->getMessage();
}

?>